package com.example.ccj.u.update;

import android.os.Environment;

import com.example.ccj.u.FileUtils;
import com.example.ccj.u.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.TimeUnit;

import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

public class DownloadUtil {
    private static final String TAG = "DownloadUtil";
    private static DownloadUtil downloadUtil;
    private final OkHttpClient okHttpClient;

    public static DownloadUtil get() {
        if (downloadUtil == null) {
            LogUtils.d(TAG,  "DownloadUtil get new DownloadUtil");
            downloadUtil = new DownloadUtil();
        }
        return downloadUtil;
    }

    private DownloadUtil() {
        okHttpClient = new OkHttpClient.Builder().
                connectTimeout(500, TimeUnit.SECONDS)
                .writeTimeout(500, TimeUnit.SECONDS)
                .readTimeout(500, TimeUnit.SECONDS)
                .build();
    }


    public void downloadUrlFile(final String url,String fileSavePath, final OnDownloadListener listener) {
        final String[] path = new String[1];

        Observable.create(new ObservableOnSubscribe<Integer>() {
            @Override
            public void subscribe(ObservableEmitter<Integer> emitter) throws Exception {
                String nameFromUrl = getNameFromUrl(url);
                path[0] = fileSavePath + nameFromUrl;
                LogUtils.d(TAG, "downloadUrlFile() 下载网络文件保存地址: " + path[0]);
                download(url, path[0], new OnDownloadListener() {
                    @Override
                    public void onDownloadSuccess(String filePath) {
                        emitter.onComplete();
                    }

                    @Override
                    public void onDownloading(int progress) {
                        emitter.onNext(progress);
                    }

                    @Override
                    public void onDownloadFailed(String error) {
                        emitter.onError(new Throwable(error));
                    }
                });
            }
        }).subscribeOn(Schedulers.newThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<Integer>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(Integer integer) {
                        listener.onDownloading(integer);
                    }

                    @Override
                    public void onError(Throwable e) {
                        listener.onDownloadFailed(e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        listener.onDownloadSuccess(path[0]);
                    }
                });
    }

    /**
     * @param url 下载连接
     * @param filePath 储存下载文件的SDCard目录
     * @param listener 下载监听
     */
    public void download(final String url, final String filePath, final OnDownloadListener listener) {
        LogUtils.d(TAG, "DownloadUtil download start");

        Request request = new Request.Builder().url(url).build();
        LogUtils.d(TAG, "DownloadUtil request:" + request.toString());
        okHttpClient.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                LogUtils.d(TAG, "DownloadUtil onFailure e:" + e.getMessage());
                listener.onDownloadFailed("DownloadUtil onFailure e:" + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                LogUtils.d(TAG, "DownloadUtil onResponse start");
                InputStream is = null;
                byte[] buf = new byte[2048];
                int len = 0;
                FileOutputStream fos = null;
                // 储存下载文件的目录
                //String savePath = isExistDir(saveDir);
                LogUtils.d(TAG, "DownloadUtil filePath:" + filePath);
                try {
                    is = response.body().byteStream();
                    long total = response.body().contentLength();
                    //File file = new File(savePath, getNameFromUrl(url));
                    File file = new File(filePath);


                    //文件不存在新建文件及文件夹
                    if (!file.exists()) {
                        FileUtils.createOrExistsFile(filePath);
                    } else {
                        listener.onDownloadSuccess(file.getAbsolutePath());
                    }

                    fos = new FileOutputStream(file);
                    long sum = 0;
                    while ((len = is.read(buf)) != -1) {
                        fos.write(buf, 0, len);
                        sum += len;
                        int progress = (int) (sum * 1.0f / total * 100);
                        // 下载中
                        listener.onDownloading(progress);
                    }
                    fos.flush();
                    // 下载完成
                    listener.onDownloadSuccess(file.getPath());
                } catch (Exception e) {
                    LogUtils.d(TAG, "DownloadUtil onResponse e1:" + e.getMessage());
                    listener.onDownloadFailed("DownloadUtil onResponse e1:" + e.getMessage());
                } finally {
                    try {
                        if (is != null) {
                            is.close();
                        }
                    } catch (IOException e) {
                        LogUtils.d(TAG, "DownloadUtil onResponse e2:" + e.getMessage());
                    }
                    try {
                        if (fos != null) {
                            fos.close();
                        }
                    } catch (IOException e) {
                        LogUtils.d(TAG, "DownloadUtil onResponse e3:" + e.getMessage());
                    }
                }
            }

        });
    }

    /**
     * @param saveDir
     * @return
     * @throws IOException
     * 判断下载目录是否存在
     */
    private String isExistDir(String saveDir) throws IOException {
        // 下载位置
        File downloadFile = new File(Environment.getExternalStorageDirectory(), saveDir);
        if (!downloadFile.mkdirs()) {
            downloadFile.createNewFile();
        }
        String savePath = downloadFile.getAbsolutePath();
        return savePath;
    }

    /**
     * @param url
     * @return
     * 从下载连接中解析出文件名
     */
    public static String getNameFromUrl(String url) {
        return url.substring(url.lastIndexOf("/") + 1);
    }

    public interface OnDownloadListener {
        /**
         * 下载成功
         */
        void onDownloadSuccess(String filePath);

        /**
         * @param progress
         * 下载进度
         */
        void onDownloading(int progress);

        /**
         * 下载失败
         */
        void onDownloadFailed(String error);
    }
}


